﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Furion.DatabaseAccessor;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using YBlog.Application.Contracts.System.Routes;
using YBlog.Core.System;

namespace YBlog.Application.System
{
    [ApiDescriptionSettings("System")]
    public class RouteService : IRouteService, IBaseService
    {
        private readonly IMemoryCacheService _memoryCache;
        private readonly IRepository<Route> _routeRepository;
        private readonly string CacheKey = "Route.AllList";


        public RouteService(IMemoryCacheService memoryCache, IRepository<Route> repository)
        {
            _memoryCache = memoryCache;
            _routeRepository = repository;
        }
        /// <summary>
        /// 根据路径获取路由
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public async Task<RouteDto> GetByPathAsync(string path)
        {
            path = HttpUtility.UrlDecode(path);
            return await Task.FromResult((await GetAll()).Find(r => r.Path == path));
        }
        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        [ApiDescriptionSettings(Name = "List")]
        public async Task<List<RouteDto>> GetListAsync(Search search)
        {
            return await Task.FromResult((from r in (await GetAll())
                                          select r).ToList());
        }
        /// <summary>
        /// 获取全部路由
        /// </summary>
        /// <returns></returns>
        [ApiDescriptionSettings(Name = "All")]
        public async Task<List<RouteDto>> GetAll()
        {
            return await _memoryCache.GetOrCreateAsync(CacheKey, async entry =>
            {
                return await (from r in _routeRepository.AsQueryable()
                              select r.Adapt<RouteDto>()
                              ).AsNoTracking().ToListAsync();
            });
        }
        /// <summary>
        /// 获取可访问路由
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [ApiDescriptionSettings(Name = "Access")]
        public async Task<List<RouteDto>> GetAccessListAsync(string token)
        {
            var allRoutes = await GetAll();
            var home = allRoutes.Find(o => o.Id == "0");
            home.Children = new List<RouteDto>();
            home.Children.AddRange(allRoutes.FindAll(o => o.Id != "0"));
            return await Task.FromResult(new List<RouteDto> { home });
        }
    }
}
